package com.ctgu.chatapp.viewModel

import android.app.Application
import android.os.Build
import android.util.Log
import android.view.View
import android.widget.PopupMenu
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.findNavController
import com.ctgu.chatapp.R
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.model.Retrofit.IMSServiceImpl
import com.ctgu.chatapp.model.Retrofit.Pojo.Friend
import com.ctgu.chatapp.model.pojo.Information
import com.ctgu.chatapp.showPojo.Contact
import com.ctgu.chatapp.showPojo.SearchFriend
import com.ctgu.chatapp.utils.Utils
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.properties.Delegates

class MainViewModel(application: Application) : AndroidViewModel(application) {


    private val TAG = "MainViewModel"
    private val imsService = IMSServiceImpl.imsServiceImpl.service
    val searchInput = MutableLiveData("")
    val searchList = MutableLiveData<List<SearchFriend>>()
    var user = MutableLiveData(
        Information(
            100000,
            "default",
            0,
            0,
            "这个人很懒,还没有填写",
            "default",
            0
        )
    )
    val data = DataBaseManager.getInstance(application)
    val friendListByName by lazy {
        data.getFriendDao().getAllFriend(chatID)
    }
    lateinit var friend: Contact
    val friendListByGroup by lazy {
        data.getFriendDao().getGroup(chatID)
    }
    val recordList by lazy {
        data.getMsgDao().getAllRecordByChatID(chatID)
    }
    val friendRequestList by lazy {
        data.getRequestDao().getFriendRequest(chatID)
    }
    private var offlineId = 0L

    init {
        viewModelScope.launch(IO) {
            async {
                do {
                    val list = imsService.getAllOffline(
                        chatID,
                        offlineId
                    )
                    if (list.isNotEmpty()) {
                        data.getMsgDao().addAllRecord(list)
                        offlineId = list[list.size - 1].id!!
                    }
                } while (list.isNotEmpty())
            }
            getSelfInformation()
            DataBaseManager.getInstance(application).getInformationDao()
                .getInformation(chatID)
                .collect {
                    user.postValue(it)
                }
        }
    }

    fun menuClick(view: View) {
        val popupMenu = PopupMenu(getApplication(), view)
        val inflater = popupMenu.menuInflater
        inflater.inflate(R.menu.pop_test, popupMenu.menu)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            popupMenu.setForceShowIcon(true)
        }
        popupMenu.show()
        popupMenu.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.addfriend -> {
                    view.findNavController().navigate(R.id.action_global_search)
                    true
                }
                else -> false
            }
        }
    }

    fun toSelfInformation(view: View) =
        view.findNavController().navigate(R.id.action_global_selfInformation)

    fun toFriendRequest(view: View) =
        view.findNavController().navigate(R.id.action_friendAGroup_to_friendRequest)

    fun searchFriend(view: View, chatID: String) {
        if (chatID == "") {
            Snackbar.make(view, "请输入后再点击", Snackbar.LENGTH_LONG).show()
        } else {
            if (chatID.toLong() == Utils.chatID) {
                Snackbar.make(view, "不能查询自己哦", Snackbar.LENGTH_LONG).show()
                return
            }
            Utils.FriendList.forEach {
                if (it.chatID == chatID.toLong()) {
                    Snackbar.make(view, "该用户您已经添加过了,不能重复发送请求", Snackbar.LENGTH_LONG).show()
                    return
                }
            }
            viewModelScope.launch(IO) {
                val list = imsService.getSearchFriend(chatID.toLong())
                searchList.postValue(list)
            }
        }
    }

    private suspend fun getSelfInformation() {
        withContext(IO) {
            val information = imsService.getInformation(chatID)
            data.getInformationDao().addInformation(information)
            //比较两个队列的差值
            val newList = imsService.getAllFriendList(chatID) //从网络获取数值
            val oldList = data.getFriendDao().getAllFriendChatID(chatID).toMutableList() //从数据库中获取数值
            val temp = newList.toMutableList()
            temp.removeAll(oldList)//得到应该添加的队列
            temp.forEach {
                val newInfo = imsService.getInformation(it.touId)
                data.getInformationDao().addInformation(newInfo)
            }
            data.getFriendDao().addFriend(temp)
            oldList.removeAll(newList)//得到应该删除的好友队列
            data.getFriendDao().deleteFriend(oldList)
            val friendList = async {
                data.getFriendDao().getAllFriendList(chatID)
            }
            addInformation(friendList.await())
        }
    }

    private suspend fun addInformation(sqlLite: List<Friend>) {
        if (sqlLite.isNotEmpty()) {
            Log.d(TAG, "addInformation: ${sqlLite.size}")
            val result = imsService.getFriendListInformation(sqlLite)
            Utils.FriendList = sqlLite
            data.getInformationDao().addFriendInformation(result)
        }
    }

    companion object {
        var chatID by Delegates.notNull<Long>()
    }

}